package org.samcolon.nettydemo.nettydemo.netty;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;

/**
 * @Description: 自定义的消息解码器
 * @author: Sam.zhang
 * @date: 2021/12/19 - 20:31
 */
@Slf4j
public class MessageDecoder extends ChannelInboundHandlerAdapter {
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (ctx == null || msg == null) {
            return;
        }

        if(msg instanceof TextWebSocketFrame){
            log.info("");
            String text = ((TextWebSocketFrame) msg).text();
            ctx.fireChannelRead(text);
            return;
        }

        if (!(msg instanceof BinaryWebSocketFrame)) {
            return;
        }

        BinaryWebSocketFrame inputFrame = (BinaryWebSocketFrame) msg;
        ByteBuf byteBuf = inputFrame.content();

        byteBuf.readShort(); //消息的长度
        int msgCode = byteBuf.readShort();

        byte[] msgBody = new byte[byteBuf.readableBytes()];
        byteBuf.readBytes(msgBody);

        switch (msgCode) {

        }
    }
}
